package com.arvin.faceDetect.ui

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.arvin.faceDetect.R
import com.arvin.faceDetect.adapter.LogFileAdapter
import com.arvin.faceDetect.databinding.FragmentLogManagementBinding
import com.arvin.faceDetect.model.LogFile
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import java.io.File

class LogManagementFragment : Fragment() {
    private var _binding: FragmentLogManagementBinding? = null
    private val binding get() = _binding!!
    private lateinit var logFileAdapter: LogFileAdapter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentLogManagementBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupToolbar()
        setupRecyclerView()
        loadLogFiles()
    }

    private fun setupToolbar() {
        binding.toolbar.setNavigationOnClickListener {
            findNavController().navigateUp()
        }

        binding.toolbar.setOnMenuItemClickListener { menuItem ->
            when (menuItem.itemId) {
                R.id.action_delete_all -> {
                    showDeleteAllConfirmDialog()
                    true
                }

                else -> false
            }
        }
    }

    private fun setupRecyclerView() {
        logFileAdapter = LogFileAdapter(
            onItemClick = { logFile ->
                openLogFile(logFile)
            },
            onItemLongClick = { logFile ->
                showDeleteConfirmDialog(logFile)
                true
            }
        )

        binding.rvLogs.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = logFileAdapter
        }
    }

    private fun loadLogFiles() {
        val logDir = File(requireContext().filesDir, "logs")
        if (!logDir.exists()) {
            updateEmptyView(true)
            return
        }

        val logFiles = logDir.listFiles()?.filter { it.isFile }?.map { LogFile(it) }
            ?.sortedByDescending { it.lastModified } ?: emptyList()
        logFileAdapter.submitList(logFiles)
        updateEmptyView(logFiles.isEmpty())
    }

    private fun updateEmptyView(isEmpty: Boolean) {
        binding.rvLogs.isVisible = !isEmpty
        binding.tvEmpty.isVisible = isEmpty
    }

    private fun openLogFile(logFile: LogFile) {
        try {
            val uri = FileProvider.getUriForFile(
                requireContext(),
                "${requireContext().packageName}.provider",
                logFile.file
            )

            val intent = Intent(Intent.ACTION_VIEW).apply {
                setDataAndType(uri, "text/plain")
                addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            }

            startActivity(Intent.createChooser(intent, "打开日志文件"))
        } catch (e: Exception) {
            Toast.makeText(context, "无法打开文件：${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    private fun showDeleteConfirmDialog(logFile: LogFile) {
        MaterialAlertDialogBuilder(requireContext())
            .setTitle("删除确认")
            .setMessage("确定要删除日志文件${logFile.name}吗？")
            .setPositiveButton("删除") { _, _ ->
                deleteLogFile(logFile)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun showDeleteAllConfirmDialog() {
        MaterialAlertDialogBuilder(requireContext())
            .setTitle("清空确认")
            .setMessage("确定要删除所有日志文件吗？")
            .setPositiveButton("删除") { _, _ ->
                deleteAllLogFiles()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun deleteLogFile(logFile: LogFile) {
        try {
            if (logFile.file.delete()) {
                Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show()
                loadLogFiles()
            } else {
                Toast.makeText(context, "删除失败", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Toast.makeText(context, "删除失败：${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    private fun deleteAllLogFiles() {
        try {
            val logDir = File(requireContext().filesDir, "logs")
            if (logDir.exists()) {
                logDir.listFiles()?.forEach { it.delete() }
            }
            Toast.makeText(context, "清空成功", Toast.LENGTH_SHORT).show()
            loadLogFiles()
        } catch (e: Exception) {
            Toast.makeText(context, "清空失败：${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 